<template>
  <div id="userManagePage" flex="auto">
    <a-flex justify="space-between" style="margin-bottom: 16px">
      <h2>空间管理</h2>
      <a-space>
        <a-button type="primary" @click="showAddModal">+ 创建空间</a-button>
      </a-space>
    </a-flex>

    <div class="module">
      <!-- 搜索框 -->
      <div class="search">
        <a-form layout="inline" :model="searchParam" @finish="doSearch">
          <a-form-item label="空间名称" name="spaceName">
            <a-input
              v-model:value="searchParam.spaceName"
              placeholder="请输入空间名称"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="空间级别" name="spaceLevel">
            <a-select
              v-model:value="searchParam.spaceLevel"
              :options="SPACE_LEVEL_OPTIONS"
              placeholder="请输入空间级别"
              style="min-width: 180px"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="用户 id" name="userId">
            <a-input v-model:value="searchParam.userId" placeholder="请输入用户 id" allow-clear />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit">搜索</a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <!-- 空间级别 -->
        <template v-if="column.dataIndex === 'spaceLevel'">
          <a-tag>{{ SPACE_LEVEL_MAP[record.spaceLevel] }}</a-tag>
        </template>
        <!-- 使用情况 -->
        <template v-if="column.dataIndex === 'spaceUseInfo'">
          <div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
          <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <!-- 分析空间 -->
            <a-button
              type="link"
              :icon="h(BarChartOutlined)"
              :href="`/space_analyze?spaceId=${record.id}`"
              target="_blank"
            >
              分析
            </a-button>
            <!-- 编辑空间 -->
            <a-button type="link" @click="showEditModal(record)">编辑</a-button>
            <!-- 删除空间 -->
            <a-button type="link" danger @click="showDeleteModal(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>

  <!-- 对话框组件 -->
  <AddSpaceDialog ref="AddSpaceDialogRef" @refresh="fetchSpaceData" />
  <EditSpaceDialog ref="EditSpaceDialogRef" @refresh="fetchSpaceData" />
  <DeleteSpaceDialog ref="DeleteSpaceDialogRef" @refresh="fetchSpaceData" />
</template>

<script lang="ts" setup>
import { computed, h, onMounted, reactive, ref } from 'vue'
import { listSpaceByPageUsingPost } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

import { useRouter } from 'vue-router'
import AddSpaceDialog from '@/pages/admin/components/AddSpaceDialog.vue'
import EditSpaceDialog from '@/pages/admin/components/EditSpaceDialog.vue'
import DeleteSpaceDialog from '@/pages/admin/components/DeleteSpaceDialog.vue'
import { SPACE_LEVEL_MAP, SPACE_LEVEL_OPTIONS } from '@/constants/space.ts'
import { formatSize } from '@/utils'
import { BarChartOutlined } from '@ant-design/icons-vue'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
    align: 'center',
  },
  {
    title: '空间名称',
    dataIndex: 'spaceName',
    align: 'center',
  },
  {
    title: '空间级别',
    dataIndex: 'spaceLevel',
    align: 'center',
  },
  {
    title: '使用情况',
    dataIndex: 'spaceUseInfo',
    align: 'center',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]

// 定义数据
const dataList = ref<API.Space[]>([])
const total = ref(0)

// 搜索条件
const searchParam = reactive<API.SpaceQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParam.current ?? 1,
    pageSize: searchParam.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

// 当表格发生变化时，刷新页面数据
const doTableChange = (page: any) => {
  searchParam.current = page.current
  searchParam.pageSize = page.pageSize
  fetchSpaceData()
}

// 获取空间信息数据
const fetchSpaceData = async () => {
  const spaceData = await listSpaceByPageUsingPost({
    ...searchParam,
  })
  if (spaceData.data.code === 0 && spaceData.data.data) {
    dataList.value = spaceData.data.data.records ?? []
    total.value = spaceData.data.data.total ?? 0
  } else {
    message.error('获取空间信息失败，' + spaceData.data.message)
  }
}

// 搜索事件
const doSearch = () => {
  searchParam.current = 1
  fetchSpaceData()
}

// 引入添加用户组件方法
const AddSpaceDialogRef = ref(null)
// 展示添加用户对话框
const showAddModal = () => {
  // 调用添加用户子组件方法
  AddSpaceDialogRef.value!.openDialog()
}

// 引入编辑子组件方法
const EditSpaceDialogRef = ref(null)
// 编辑用户所需参数
const editSpaceParam = ref<API.SpaceUpdateRequest>()
// 展示编辑用户对话框
const showEditModal = (record: API.SpaceUpdateRequest) => {
  editSpaceParam.value = record
  // 调用编辑子组件方法
  EditSpaceDialogRef.value!.openDialog(editSpaceParam.value)
}

// 引入删除子组件方法
const DeleteSpaceDialogRef = ref(null)
// 删除空间所需参数
const deleteId = ref<number>(0)
// 展示删除空间对话框
const showDeleteModal = (id: number) => {
  // 调用删除子组件方法
  DeleteSpaceDialogRef.value!.openDialog(id)
}

// 钩子函数，页面加载时获取数据
onMounted(() => {
  fetchSpaceData()
})
</script>

<style scoped>
.module {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.search {
  margin-left: 20px;
}

.action {
  width: 80px;
  margin: 0 auto;
}

.tags-tab {
  width: 80px;
  margin: 0 auto;
}
</style>
